import random

from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import HttpResponse, HttpResponseBadRequest
from django_redis import get_redis_connection


# Create your views here.
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from .serializers import SMSCodeSerializer


class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        # 1.生成图片验证码
        text, image_data = captcha.generate_captcha()
        # 2.保存验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('image_code_%s' % image_code_id, 300, text)
        # 返回
        response = HttpResponse(image_data)
        response['Content-Type'] = 'image/png'

        return response


class SMSCodeView(GenericAPIView):
    serializer_class = SMSCodeSerializer
    def get(self, request, mobile):
        dict_data = request.query_params

        # 创建序列化器,校验
        serializer = self.get_serializer(data=dict_data)

        serializer.is_valid(raise_exception=True)

        sms_code = "%06s" % random.randint(0, 999999)
        redis_conn = get_redis_connection('code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'errmsg': '频繁发送'}, status=status.HTTP_400_BAD_REQUEST)
        # 使用celery处理短信发送
        # from celery_tasks.sms.tasks import send_sms_code
        # send_sms_code(mobile, sms_code)
        #######
        # result = CCP().send_template_sms(to=mobile, datas=[sms_code, 6], temp_id=1)
        # if result == -1:
        #     return HttpResponseBadRequest('发送失败')
        print(sms_code)
        # 短信入库
        redis_conn.setex('send_flag_%s' % mobile, 60, True)
        redis_conn.setex('sms_code_%s' % mobile, 300, sms_code)
        return Response(status=status.HTTP_200_OK)
